<template>
    <el-container>
        <el-header>
            <div class="menu">
                <el-menu class="el-menu-demo" mode="horizontal" text-color="#303133" >
                <el-menu-item  >Suhan's桌面背景分享上传</el-menu-item>
                <el-menu-item >
                        <el-input placeholder="请输入内容" v-model="input" >
                            <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
                        </el-input>
                </el-menu-item>
               
                </el-menu>
            </div>
        </el-header>
        <el-main>
            <div class="content">
                
              <el-upload
                class="upload-demo"
                :http-request="upload"
                :show-file-list="false"
                :before-upload="beforeUpload"
                :on-change="changeData"
                list-type="picture">
                <el-button size="small" type="primary">点击上传<i class="el-icon-upload el-icon--right"></i></el-button>
                <div slot="tip" class="el-upload__tip"  style="height:30px;">图片文件上传，且不超过5M</div>
             </el-upload>
             <el-progress v-show="progressFlag" :stroke-width="3" :percentage="progressPercent" ></el-progress>

             <!--图片展示-->
              <el-row :gutter="20" >
                    <el-col  :span="6"  v-for="item in fileList" :key="item.index">
                       
                            <div class="demo-image__error">
                            <div class="block__lazy" >
                                <div class="demonstration" style="padding-top:10px;padding-bottom:10px">
                                    <span class="over-text">名称：<a href="javascript:void(0)" @click="ondown(item.id,item.image_name,item.image_url)">{{item.image_name | ellipsis}}</a></span>
                                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <span class="over-text">上传时间：{{item.pub_time}}</span>                                                           
                                </div>
                                
                                <el-image 
                                    style="width:300px;height:220px;border-radius: 4px;"
                                    :src="item.image_url" 
                                    :preview-src-list="srcList" @click="onclick(item.image_url)">
                                </el-image>
                            </div>
                            </div> 
                     </el-col> 
                </el-row>  
            </div>     
        </el-main>
    </el-container>
</template>


<script>
  export default {
    data() {
      return {
        input:"",
        dialogVisible: false,
        progressPercent:0,
        progressFlag:false,
        srcList: [],
        fileList: [],      
      };
    },

    //字符串过滤器
    filters: {
            ellipsis (value) {
            if (!value) return ''
            if (value.length > 8) {
                return value.slice(0,6) + '...'
            }
            return value
            }
        },

    methods: {

        upload(content){
            self = this;
            const params = new FormData();
            params.append("upload_file", content.file);
            const config = {
                    onUploadProgress: progressEvent => {
                    // progressEvent.loaded:已上传文件大小
                    // progressEvent.total:被上传文件的总大小
                    this.progressPercent = Number((progressEvent.loaded / progressEvent.total * 100).toFixed(2))
                    }
                }
            self.progressFlag = true
            this.$axios.post("/upload", params ,config ).then(res =>{

                if(res.data.status_code==200){
                    let data = {
                        "id":res.data.msg.id,
                        "image_name":res.data.msg.image_name,
                        "image_url":res.data.msg.image_url,
                        "pub_time":res.data.msg.pub_time
                    }
                    self.fileList.push(data)
                    self.$message({
                    message: '恭喜你，图片上传成功！',
                    type: 'success'
                    });
                    self.progressFlag = false
                }else{
                    self.$message.error(res.data.msg);
                }

                console.log(res.data)
            }).catch(err =>{
                console.log(err)
            })
        },

        
        beforeUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 5;
            if (!isLt2M) {
                this.$message.error('上传文件大小大小不能超过 5MB!');
                return isLt2M;
            }
        },

        changeData (file) {
            // 数据小于0.1M的时候按KB显示
            const size = file.size/1024/1024 > 0.1 ? '(${(file.size/1024/1024).toFixed(1)}M)':'(${(file.size/1024).toFixed(1)}KB)'
            file.name.indexOf('M')> -1 || file.name.indexOf('KB')>-1 ? file.name : file.name += size
        },

        
        handleRemove(file, fileList) {
            console.log(file, fileList);
        },
        handlePreview(file) {
            console.log(file);
        },


        ondown(id, filename, down_url){
            this.$axios({
            method: 'GET',
            url: '/updown?id=' + id,
            responseType: 'blob'
          }).then(res=>{
            const blob = new Blob([res.data])
            let url = window.URL.createObjectURL(blob)

            //创建一个a标签元素，设置下载属性，点击下载，最后移除该元素
            let link = document.createElement('a')
            link.href = url
            link.style.display = 'none'
            var fileExtension = down_url.substring(down_url.lastIndexOf('.') + 1);
            const downlaodFileName = filename + "." + fileExtension
            console.log(res)
            link.setAttribute('download',downlaodFileName)
            link.click()
            window.URL.revokeObjectURL(url)
          }).catch((res)=>{
            console.log(res)
            this.$message.error("下载失败")
          })
           
        
        },

        onclick(url){
            this.srcList.push(url)
        },

        search(){

            self = this;
            this.$axios.post('/search', {image_name:self.input}).then(res=>{
                    if(res.data.status_code==200){
                        self.fileList = res.data.msg.data
                        console.log(res.data.msg.data)
                    }else{
                        self.$message.error(res.data.msg);
                    }
                })

        }
      
    },

    mounted:function(){
        self = this;
        this.$axios.post('/search', {image_name:''}).then(res=>{
                if(res.data.status_code==200){
                    self.fileList = res.data.msg.data
                    console.log(res.data.msg.data)
                }else{
                    self.$message.error(res.data.msg);
                }
            })
    }

  }
</script>


<style scoped>

    .menu{
        width: 72%;
        margin: auto;
       
    }

    .content{
        width: 70%;
        margin: auto;
    }

    .el-menu-item {
        font-size: 24px;
    }


    /**图片展示 */


    .over-text{
        font-size: 12px;
        color:cadetblue;
    } 


</style>
